<?php
namespace app\common\model;

use app\common\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class PaymentSetting extends BaseModel
{
    public static $fieldTypes = [
        'id' => 'number',
        'aid' => 'number',
        'status' => 'number',
        'created_at' => 'date',
    ];

    /**
     * 保存数据
     * @param $data
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function saveData($data)
    {
        $curUserId = request()->user['user_id'];

        if(empty($data['id'])) {
            if(empty($data['quota']) || !is_array($data['quota'])) {
                throw new Exception('支付设置不能为空');
            }

            array_map(function($item) {
                if(!is_numeric($item) || $item < 0) {
                    throw new Exception('支付面额必须是大于零的数字类型');
                }
            }, $data['quota']);

            self::insertGetId([
                'aid' => $curUserId,
                'priority' => isset($data['priority']) ? $data['priority'] : 0,
                'status' => self::DISABLED_STATUS,
                'pay_url' => !empty($data['pay_url']) ? $data['pay_url'] : '',
                'quota' => json_encode($data['quota'], 256),
            ]);
        }else{
            if(!$modelRecord = self::findById($data['id'])) {
                throw new Exception('支付设置不存在');
            }

            if(!empty($data['pay_url'])) {
                $modelRecord->pay_url = $data['pay_url'];
            }

            if(isset($data['priority'])) {
                $modelRecord->priority = $data['priority'];
            }

            if(!empty($data['quota'])) {
                if(!is_array($data['quota'])) {
                    throw new Exception('支付面额格式有误');
                }

                array_map(function($item) {
                    if(!is_numeric($item) || $item < 0) {
                        throw new Exception('支付面额必须是大于零的数字类型');
                    }
                }, $data['quota']);

                $modelRecord->quota = json_encode($data['quota'], 256);
            }

            if(isset($data['status'])) {
                $modelRecord->status = $data['status'];
            }

            $modelRecord->save();
        }
    }
}